import {createWebHashHistory, createRouter, createWebHistory} from "vue-router";
import index from '../view/index.vue'
import user from '../view/User.vue'
import classification from '../view/Classification.vue'
import post from '../view/Post.vue'
import posthouse from '../view/PostHouse.vue'
import login from '../view/Login .vue'
import myself from '../view/Myself.vue'
import postcreate from '../view/PostCreate.vue'
import myselfpost from '../view/MyselfPost.vue'
import register from '../view/Register.vue'
import changePassword from '../view/ChangePassword.vue'
import loginApi from '../api/Login_api.js'
import email from '../view/ResetPasswordByEmail.vue'
// 导入消息中心组件
import messagecenter from '../view/MessageCenter.vue'

// 公共路由（所有用户都能访问）
// 在 publicRoutes 中添加消息中心路由
const publicRoutes = [
    { path: '/PostHouse', component: posthouse, name: 'PostHouse' },
    { path: '/Myself', component: myself, name: 'Myself' },
    { path: '/PostCreate', component: postcreate, name: 'PostCreate' },
    { path: '/MyselfPost', component: myselfpost, name: 'MyselfPost' },
    { path: '/ChangePassword', component: changePassword, name: 'ChangePassword' },
    { path: '/MessageCenter', component: messagecenter, name: 'MessageCenter' }, // 新增
];

// 管理员专属路由
const adminRoutes = [
    { path: '/User', component: user, name: 'User' },
    { path: '/Classification', component: classification, name: 'Classification' },
    { path: '/Post', component: post, name: 'Post' },
];

const routes = [
    {
        path: '/login',
        name: 'login',
        component: login
    },
    {
        path: '/register',
        name: 'register',
        component: register
    },
    {
        path: '/reset-password-email',
        name: 'ResetPasswordByEmail',
        component: email
    },
    {
        path: '/',
        name: 'index',
        component: index,
        children: [
            // 先添加公共路由，避免初始路由为空
            ...publicRoutes
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/PostHouse'
    }
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

// 使用 Map 来存储已添加的路由状态
const addedRoutes = new Map();

// 动态添加路由的函数 - 修复版本
function addRoutesBasedOnRole(role) {
    const indexRoute = router.getRoutes().find(route => route.name === 'index');
    if (!indexRoute) return;

    // 检查是否已经为该角色添加过路由
    if (addedRoutes.has(role)) {
        return;
    }

    // 标记该角色的路由已添加
    addedRoutes.set(role, true);

    // 如果是管理员，添加管理员路由
    if (role === 'administrator') {
        adminRoutes.forEach(route => {
            // 检查路由是否已存在
            if (!router.hasRoute(route.name)) {
                router.addRoute('index', route);
            }
        });
    }
}

router.beforeEach(async (to, from, next) => {
    const token = localStorage.getItem("token");
    const whiteList = ['/login', '/register', '/reset-password-email'];

    // 如果访问登录或注册页，直接放行
    if (whiteList.includes(to.path)) {
        next();
        return;
    }

    // 如果未登录且不是访问公开页面，跳转到登录
    if (!token) {
        next('/login');
        return;
    }

    try {
        const user = await loginApi.loginInfo();

        // 动态添加路由（基于角色）
        addRoutesBasedOnRole(user.role);

        // 检查权限：如果是管理员路由但用户不是管理员，重定向到首页
        const isAdminRoute = adminRoutes.some(route => route.path === to.path);
        if (isAdminRoute && user.role !== 'administrator') {
            next('/PostHouse');
            return;
        }

        // 正常放行
        next();
    } catch (error) {
        console.error("获取用户信息失败", error);
        localStorage.removeItem("token");

        // 避免重定向到当前页面导致循环
        if (to.path !== '/login') {
            next('/login');
        } else {
            next();
        }
    }
});

export default router;